<template>
  <div class="page-container">
    <el-container>
      <el-aside class="page-aside" width="280px" v-drag v-collapse>
        <div class="title">
          <div class="title-content">字典</div>
          <div class="title-button">
            <div class="button-list">
              <div class="button-item">
                <ac-icon
                  iconId="018dca412c4e207388f7"
                  :style="'cursor: pointer;color: ' + (treeCheck ? 'rgb(0,133,246)' : '#999') + ';font-size: 18px;'"
                  :title="treeCheck ? '导入模式' : '导出模式'"
                  @click.stop="changeMode"
                />
              </div>
              <div class="button-item">
                <ac-icon
                  iconId="018ece4f749ec5911772"
                  style="cursor: pointer;color: rgb(0,133,246); font-size: 18px;"
                  title="导出字典"
                  @click.stop="handleExport"
                />
              </div>
              <div class="button-item">
                <el-upload
                  action=""
                  :http-request="handleImport"
                  :show-file-list="false"
                  accept=".dat"
                >
                  <ac-icon
                    iconId="018ece4f70fcf0627f81"
                    style="cursor: pointer;color: rgb(0,133,246); font-size: 18px;"
                    title="导入字典"
                  />
                </el-upload>
              </div>
            </div>
            <span class="title-button-box" @click="addDictionary({})">
              <el-tooltip placement="bottom" content="新增字典">
                <ac-icon iconId="018dc9c3efed46e8b927" size="18" />
              </el-tooltip>
            </span>
          </div>
        </div>
        <div class="filter-box">
          <el-input placeholder="搜索" v-model="filterText" clearable />
        </div>
        <div class="page-aside-grow">
          <el-tree
            ref="tree"
            class="tree"
            node-key="id"
            v-loading="treeLoading"
            element-loading-text="数据加载中..."
            :data="treeData"
            :props="treeProps"
            :highlight-current="true"
            :default-expanded-keys="treeExpand"
            :filter-node-method="filterNode"
            @node-click="nodeClick"
            :show-checkbox="treeCheck"
          >
            <template v-slot="{ node, data }">
              <div class="node-item">
                <span class="icon">
                  <ac-icon v-if="node.expanded" color="orange" iconId="018dc9c3efedbb59d0b3" />
                  <ac-icon v-else color="orange" iconId="018dc9c3efedbb59d0b3" />
                </span>
                <span class="node-label" :title="data.text"><span>{{data.text}}</span></span>
                <div class="node-button">
                  <el-dropdown trigger="hover" placement="bottom-start">
                    <span class="node-button-item">
                      <ac-icon iconId="018dca6283a1e534a046" @click.stop />
                    </span>
                    <template #dropdown>
                      <el-dropdown-menu>
                        <el-dropdown-item @click="addDictionary(data.data)">
                          <ac-icon iconId="018dc9c3efedbb59d0b3" color="orange" style="margin-right: 5px" />新增字典
                        </el-dropdown-item>
                        <el-dropdown-item @click="editDictionary(data.data)">
                          <ac-icon iconId="018dca6db20c6a3aaf68" color="#0085f6" style="margin-right: 5px" />修改字典
                        </el-dropdown-item>
                        <el-dropdown-item @click="deleteDictionary(data.data)">
                          <ac-icon iconId="018dc9c3efd3a0502886" color="#F56C6C" style="margin-right: 5px" />删除字典
                        </el-dropdown-item>
                      </el-dropdown-menu>
                    </template>
                  </el-dropdown>
                </div>
              </div>
            </template>
          </el-tree>
        </div>
      </el-aside>
      <el-main class="page-main">
        <ac-table
          ref="dataTable"
          pkName="id"
          :filters="filters"
          :filterFields="filterFields"
          :columns="columns"
          :defaultSort="defaultSort"
          @handleTableOperator="handleTableOperator"
          @handleAjaxSuccess="handleAjaxSuccess"
        ></ac-table>
      </el-main>
    </el-container>
  </div>

  <!--新增/编辑字典界面-->
  <el-dialog
    v-model="dictionaryVisible"
    :title="dictionaryTitle"
    width="600px"
    :close-on-click-modal="false"
    destroy-on-close
    draggable
  >
    <el-form
      ref="dictionaryForm"
      label-width="120px"
      label-position="right"
      :model="dictionaryData"
      :rules="dictionaryRules"
    >
      <el-row v-if="dictionaryData.id">
        <el-col :span="24">
          <el-form-item label="字典编码" prop="id">
            <el-input disabled v-model="dictionaryData.id" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="字典名称" prop="name">
            <el-input v-model="dictionaryData.name" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="上级字典" prop="parentId">
            <ac-tree
              v-model="dictionaryData.parentId"
              data-url="/system/dictionary/queryTree"
              :leafSelect="false"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="字典描述" prop="description">
            <el-input v-model="dictionaryData.description" type="textarea" :rows="5" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button
        size="default"
        type="info"
        @click="dictionaryVisible=false"
      >取消</el-button>
      <el-button
        type="primary"
        size="default"
        :loading="dictionaryLoading"
        @click="submitDictionaryForm"
      >提交</el-button>
    </template>
  </el-dialog>

  <el-dialog
    v-model="dataDialogVisible"
    :title="dataDialogTitle"
    width="500px"
    :close-on-click-modal="false"
    destroy-on-close
    draggable
  >
    <el-form
      ref="dataDataForm"
      label-width="120px"
      label-position="right"
      :model="dataFormData"
      :rules="dataRules"
    >
      <el-row>
        <el-col :span="24">
          <el-form-item label="上级数据键" prop="dictParent">
            <el-input v-model="dataFormData.dictParent" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="数据键" prop="dictKey">
            <el-input v-model="dataFormData.dictKey" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="数据值" prop="dictValue">
            <el-input v-model="dataFormData.dictValue" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="标签颜色" prop="color">
            <el-color-picker v-model="dataFormData.color" :predefine="predefineColors" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="排序" prop="ordinal">
            <el-input v-model.number="dataFormData.ordinal" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button
        size="default"
        type="info"
        @click="dataDialogVisible=false"
      >取消</el-button>
      <el-button
        type="primary"
        size="default"
        :loading="editLoading"
        @click="submitDataForm"
      >提交</el-button>
    </template>
  </el-dialog>

  <el-dialog
    :title="batchDialogTitle"
    width="900px"
    v-model="batchDialogVisible"
    :close-on-click-modal="false"
    class="batch-dialog"
    destroy-on-close
    draggable
  >
    <div>
      <div style="margin-bottom: 5px;">
        <span>新增&nbsp;
        <el-input
          v-model.number="newRow"
          size="default"
          style="width:50px"
        ></el-input>&nbsp;行&nbsp;</span>
        <el-button size="default" type="success" @click="addNew">添加 {{newRow}} 行</el-button>
        <el-tooltip>
          <template #content>
            剪切板格式，一搬从excel直接复制，有2列、3列、4列3种格式方式。分割符为空格、tab。<br/>
            只有2列时为：数据键、数据值。<br/>
            只有3列时为：数据键、数据值、排序。<br/>
            只有4列时为：上级数据键、数据键、数据值、排序。<br/>
          </template>
          <el-button
            type="success"
            size="default"
            @click="createFromClipboard"
          >从剪切板生成</el-button>
        </el-tooltip>
      </div>
      <el-form
        :model="batchFormData"
        label-width="0px"
        ref="batchDataForm"
        label-position="right"
      >
        <el-table
          class="edit-table"
          style="width:100%"
          :data="batchFormData.list"
          width="100%"
          :border="true"
        >
          <el-table-column label="上级数据键" header-align="center" width="200">
            <template v-slot="{ row, $index }">
              <el-form-item :prop="'list.' + $index +'.dictParent'" :rules="batchRules.dictParent">
                <el-input v-model="row.dictParent" />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="数据键" header-align="center" width="200">
            <template v-slot="{ row, $index }">
              <el-form-item :prop="'list.' + $index +'.dictKey'" :rules="batchRules.dictKey">
                <el-input v-model="row.dictKey" />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="数据值" header-align="center" min-width="200">
            <template v-slot="{ row, $index }">
              <el-form-item :prop="'list.' + $index +'.dictValue'" :rules="batchRules.dictValue">
                <el-input v-model="row.dictValue" />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="标签颜色" header-align="center" align="center" width="90">
            <template v-slot="{ row }">
              <el-form-item>
                <el-color-picker v-model="row.color" :predefine="predefineColors" />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="排序" header-align="center" width="90px">
            <template v-slot="{ row, $index }">
              <el-form-item :prop="'list.' + $index +'.ordinal'" :rules="batchRules.ordinal">
                <el-input v-model.number="row.ordinal" />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="80" header-align="center" align="center">
            <template v-slot="{ row }">
              <el-button
                type="danger"
                @click="handleDeleteRow(row)"
                link
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
    </div>
    <template #footer>
      <el-button
        size="default"
        type="info"
        @click="batchDialogVisible=false"
      >取消</el-button>
      <el-button
        type="primary"
        size="default"
        :loading="editLoading"
        @click="submitBatchForm"
      >提交</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, nextTick, watch, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from "element-plus";
import api from '@/http/api';
import { clearDictionary } from '@/utils/system';
import tool from "@/utils/tool";

const tree = ref();
const filterText = ref('');
const treeLoading = ref(false);
const treeKey = ref('');
const treeData = ref([]);
const treeExpand = ref([]);
const treeCheck = ref(false);
const treeProps = ref({
  children: 'children',
  label: 'text'
});

const dictionaryTitle = ref('');
const dictionaryVisible = ref(false);
const dictionaryLoading = ref(false);
const dictionaryForm = ref();
const dictionaryData = ref({});
const dictionaryRules = ref({
  name: [{required: true, message: '请输入字典名称', trigger: 'blur'}],
});

const batchDataForm = ref();
const dataDataForm = ref();

const dataTable = ref();
const filters = ref({
  folderId: '',
  name: '',
});
const filterFields = ref([
  {prop: "dictName", label: "字典名称"},
  {prop: "dictKey", label: "数据键"},
  {prop: "dictValue", label: "数据值"},
]);
const columns = ref([
  {prop: "dictName", label: "字典名称", minWidth: 100},
  {prop: "dictParent", label: "上级数据键", minWidth: 120},
  {prop: "dictKey", label: "数据键", minWidth: 120},
  {prop: "dictValue", label: "数据值", minWidth: 140, formatterHtml: (prop, value, data) => {
      return data.color ? `<span
          style="color: white;padding: 5px 10px;border-radius: 5px;background: ${data.color};"
        >${value}</span>` : value;
    }
  },
  {prop: "color", label: "标签颜色", width: 140, type: 'color'},
  {prop: "ordinal", label: "排序", minWidth: 80, type: 'number'},
  {prop: "updateTime", label: "更新时间", width: 160, type: "datetime"}
]);
const defaultSort = ref({prop: 'ordinal', order: 'ascending'});
const editLoading = ref(false);
const dataDialogVisible = ref(false);
const dataDialogTitle = ref('');
const dataRules = ref({
  dictKey: [{required: true, message: '请输入数据键', trigger: 'blur'}],
  dictValue: [{required: true, message: '请输入数据值', trigger: 'blur'}],
  ordinal: [
    {required: true, message: '请输入排序', trigger: 'blur'},
    {type: 'number', message: '排序必须为数字', trigger: 'blur'}]
})
const dataFormData = ref({});

const newRowFlag = ref(1);
const newRow = ref(1);
const batchDialogTitle = ref('');
const batchDialogVisible = ref(false);
const batchRules = ref({
  dictKey: [{required: true, message: '请输入数据键', trigger: 'blur'}],
  dictValue: [{required: true, message: '请输入数据值', trigger: 'blur'}],
  ordinal: [
    {required: true, message: '请输入排序', trigger: 'blur'},
    {type: 'number', message: '排序必须为数字', trigger: 'blur'}]
});
const batchFormData = ref({
  dictId: '',
  list: []
});

const predefineColors = ref([
  '#42A5F5',
  '#26A69A',
  '#2FCD6E',
  '#E91E63',
  '#BA68C8',
  '#9C27B0',
  '#FF9800',
  '#303F9F',
  '#795548',
  '#666666',
]);

const changeMode = () => {
  treeCheck.value = !treeCheck.value;
  if (treeCheck.value) {
    tree.value.setCheckedNodes([]);
  }
}

const handleExport = () => {
  let nodes = tree.value.getCheckedNodes(false, true);
  if (!nodes || nodes.length === 0) {
    ElMessage.error("请先选择字典！");
    return;
  }
  let data = nodes.map(item => item.id);
  api.downloadFile('/system/dictionary/exportData', {ids: data}).then(res => api.saveFileLocal(res));
};

const handleImport = (file) => {
  api.uploadFile('/system/dictionary/importData', {'file': file.file}).then((res) => {
    ElMessage.success(res.message);
    loadTreeData();
    dataTable.value.findPage();
  });
};

const filterNode = (value, data) => {
  if (!value) return true;
  return data.text.indexOf(value) >= 0;
};

const currNode = ref(null);
const nodeClick = (data, treeNode) => {
  if (currNode.value && currNode.value.id === data.id) {
    treeNode.checked = !treeNode.checked;
  } else {
    treeNode.checked = true;
  }

  if (treeNode.checked) {
    currNode.value = data;
    filters.value.dictId = data.id || '';
    dataTable.value.refreshPage(1);
  } else {
    tree.value.setCurrentKey(null);
    currNode.value = null;
    filters.value.dictId = '';
    dataTable.value.refreshPage(1);
  }
};

const addDictionary = (data) => {
  dictionaryData.value = {parentId: data.id || '', ordinal: 10};
  dictionaryTitle.value = "新增字典";
  dictionaryVisible.value = true;
  dictionaryForm.value && dictionaryForm.value.resetFields();
};

const editDictionary = (data) => {
  dictionaryData.value = Object.assign({}, data);
  dictionaryTitle.value = "修改字典";
  dictionaryVisible.value = true;
  dictionaryForm.value && dictionaryForm.value.resetFields();
};

const deleteDictionary = (data) => {
  let url = '/system/dictionary/delete';
  ElMessageBox.confirm('请确认是否删除【' + data.name + '】？', '提示', {type: 'warning'}).then(() => {
    api.post(url, {id: data.id}).then(res => {
      ElMessage.success(res.message);
      treeExpand.value.push(data.folderId || '0');
      treeExpand.value.push(data.parentId || '0');
      treeKey.value = data.parentId || data.folderId || '0';
      loadTreeData();
    });
  }).catch(() => {});
};

const submitDictionaryForm = () => {
  dictionaryForm.value && dictionaryForm.value.validate((valid) => {
    if (valid) {
      ElMessageBox.confirm('请确认是否提交？', '提示', {type: 'info'}).then(() => {
        dictionaryLoading.value = true;
        api.post('/system/dictionary/save', dictionaryData.value).then(res => {
          ElMessage.success(res.message);
          currNode.value = res.data || {};
          filters.value.dictId = res.data.id;
          dictionaryVisible.value = false;
          dictionaryLoading.value = false;
          treeExpand.value.push(res.data.id || '0');
          treeKey.value = res.data.id || '0';
          loadTreeData();
          dataTable.value.findPage();
          dictionaryDataChange();
        }).catch(() => {
          dictionaryLoading.value = false;
        });
      }).catch(() => {
      });
    }
  });
};

const handleTableOperator = (button, row) => {
  if ((button.buttonType === 'add' || button.buttonType === 'batchEdit')
    && (filters.value.dictId === undefined
      || filters.value.dictId == null
      || filters.value.dictId === '')) {
    ElMessage.error('请先选择右侧字典！');
    return;
  }

  if (button.buttonType === 'batchEdit') {
    batchDialogVisible.value = true;
    batchDialogTitle.value = button.name;
    let list = [{newRowFlag: ++newRowFlag.value}];
    if (row && row.length > 0) {
      list = tool.deepClone(row);
    }
    batchFormData.value = {
      dictId: filters.value.dictId,
      list: list,
      button: button
    };
    nextTick(() => {
      if (batchDataForm.value) {
        batchDataForm.value.clearValidate();
      }
    });
  } else {
    dataDialogVisible.value = true;
    dataDialogTitle.value = button.name;
    if (button.buttonType === 'edit') {
      dataFormData.value = Object.assign({}, row, {button: button})
    } else {
      dataFormData.value = {dictId: filters.value.dictId, button: button};
    }

    nextTick(() => {
      if (dataDataForm.value)
        dataDataForm.value.clearValidate();
    });
  }
};

const handleAjaxSuccess = () => {
  dictionaryDataChange();
  dataTable.value.findPage();
};

const dictionaryDataChange = () => {
  clearDictionary();
};

const addNew = () => {
  for (let i=0;i<newRow.value;i++) {
    batchFormData.value.list.push({newRowFlag: ++newRowFlag.value});
  }
}

const handleDeleteRow = (row) => {
  for (let i=0;i<batchFormData.value.list.length;i++) {
    if (row.newRowFlag !== undefined && row.newRowFlag === batchFormData.value.list[i].newRowFlag) {
      batchFormData.value.list.splice(i, 1);
      return;
    }
  }
}

const submitDataForm = () => {
  dataDataForm.value.validate((valid) => {
    if (valid) {
      ElMessageBox.confirm('请确认是否提交？', '提示', {type: 'info'}).then(() => {
        editLoading.value = true
        api.post(dataFormData.value.button.dataDestUrl, dataFormData.value).then(res => {
          ElMessage.success(res.message);
          dataDialogVisible.value = false;
          dataDataForm.value.resetFields();
          dataTable.value.findPage();
          editLoading.value = false;
          dictionaryDataChange();
        }).catch(() => {
          editLoading.value = false;
        });
      }).catch(()=>{});
    }
  })
}

const createFromClipboard = () => {
  navigator.clipboard.readText().then(text => {
    if (!text) return;
    let i = 0;
    text.split(/[\r\n]/).map(line => line.split(/[ \t]/)).forEach(item => {
      if (!item || item.length <= 1) return;

      let data = {};
      if (item.length === 2) {
        data = {
          dictKey: item[0],
          dictValue: item[1],
          ordinal: ++i,
          newRowFlag: ++newRowFlag.value
        }
      } else if (item.length === 3) {
        data = {
          dictKey: item[0],
          dictValue: item[1],
          ordinal: item[2],
          newRowFlag: ++newRowFlag.value
        }
      } else if (item.length === 4) {
        data = {
          dictParent: item[0],
          dictKey: item[1],
          dictValue: item[2],
          ordinal: parseInt(item[3] || '0'),
          newRowFlag: ++newRowFlag.value
        }
      }

      if (data.newRowFlag) {
        batchFormData.value.list.push(data);
      }
    });
  }).catch(err => console.error('读取剪切板内容时发生错误：', err));
};

const submitBatchForm = () => {
  batchDataForm.value.validate((valid) => {
    if (valid) {
      ElMessageBox.confirm('请确认是否提交？', '提示', {type: 'info'}).then(() => {
        editLoading.value = true;
        api.post(batchFormData.value.button.dataDestUrl, batchFormData.value).then(res => {
          ElMessage.success(res.message);
          batchDialogVisible.value = false;
          batchDataForm.value.resetFields();
          dataTable.value.findPage();
          editLoading.value = false;
          dictionaryDataChange();
        }).catch(() => {
          editLoading.value = false;
        })
      }).catch(()=>{});
    }
  });
}

const loadTreeData = () => {
  treeLoading.value = true;
  api.post('/system/dictionary/queryTree').then(res => {
    let node = tree.value.getCurrentNode();
    if (node !== undefined && node != null) {
      treeExpand.value = [node.id, node.data.parentId, node.data.folderId, '0'];
    } else {
      treeExpand.value = ['0'];
    }
    treeData.value = res.data.children;
    treeLoading.value = false;
    if (treeKey.value) {
      nextTick(() => {
        tree.value.setCurrentKey(treeKey.value);
      });
    }
  }).catch(() => {
    treeLoading.value = false;
  });
};

watch(() => filterText.value, val => {
  tree.value.filter(val);
});

onMounted(() => {
  loadTreeData();
});
</script>

<style scoped lang="scss">
.title {
  display: flex;
  flex-direction: row;
  margin-right: 10px;
  height: 40px;
  align-items: center;

  .title-content {
    flex-grow: 1;
    font-size: 18px;
  }
  .title-button {
    display: flex;
    flex-direction: row;
    justify-content: center;
    align-items: center;
  }
  .title-button .button-list {
    display: flex;
    flex-direction: row;
    align-items: center;
    .button-item {
      margin: 0 5px 0 5px;
    }
  }
  .title-button .title-button-box {
    height: 30px;
    width: 40px;
    border-radius: 5px;
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: center;
    border: none;
    cursor: pointer;
  }

  .title-button .title-button-box:hover {
    background: #eaeaea;
    border: none;
  }

  .title-button .title-button-box:focus-visible {
    outline: unset;
  }
}

.filter-box {
  margin-right: 10px;
}

.tree :deep(.el-tree-node__content) {
  height: 40px;
}

.page-aside-grow {
  width: 100% !important;

  :deep(.el-tree) {
    display: flex;
    flex-direction: column;
    width: 1px !important;
  }

  :deep(.el-tree-node) {
    display: flex;
    flex-direction: column;
    width: 100% !important;
  }

  :deep(.el-tree-node__content) {
    display: flex;
    flex-grow: 1;
  }
}

.node-item {
  display: flex;
  flex-direction: row;
  align-items: center;
  width: 100%;

  .icon {
    display: flex;
    align-items: center;
  }

  .node-label {
    margin-left: 6px;
    flex-grow: 1;
    width: 1px;
    text-overflow: ellipsis;
    overflow: hidden;
    display: flex;

    > span {
      width: 100%;
      text-overflow: ellipsis;
      overflow: hidden;
    }
  }
  .node-button .node-button-item {
    height: 30px;
    width: 40px;
    display: flex;
    justify-content: center;
    align-items: center;
    border-radius: 5px;
  }
  .node-button .node-button-item:focus-visible {
    outline: unset;
  }
}
:deep(.el-tree-node:not(.is-current):focus>.el-tree-node__content) {
  background-color: unset!important;
}
:deep(.el-tree-node:focus>.el-tree-node__content) {
  background-color: unset!important;
}
:deep(.el-tree-node:focus>.el-tree-node__content:hover) {
  background-color: #f5f7fa!important;
}
:deep(.el-tree-node.is-current:focus>.el-tree-node__content) {
  background-color: #ecf5ff!important;
}
.node-item:hover {
  .node-button .node-button-item:hover {
    background: #eaeaea;
  }
}
.dict-label {
  display: block;
  padding: 5px 10px;
  border-radius: 5px;
  color: white;
}
</style>